package com.zhoufeng.schedule;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.TimerTask;

import com.zhoufeng.db.JDBCUtilSingle;

public class MonitDeviceOnlineOrOffLineTask extends TimerTask {
	
	@Override
	public void run() {
		Connection con = JDBCUtilSingle.getInitJDBCUtil().getConnection(false);
		PreparedStatement pstmt = null, updatepstmt = null,updatesetpstmt = null;
		ResultSet rs = null;
		String sql = "select * from thing_device where onoroff = 1";//只监控在线的设备是否离线，离线设备在收到设备信息时会自动转为在线
		String updatesql = "update thing_device set onoroff = ? where id = ? and onoroff = ?";
//		String updatesetsql = "update thing_device_info set setonoroff = 3 where id = ? ";
		
		try {
			pstmt = con.prepareStatement(sql);
			updatepstmt = con.prepareStatement(updatesql);
			
			rs = pstmt.executeQuery();
			
			Date date = new Date();
			
			Calendar cal =Calendar.getInstance();
			cal.setTime(date);
			
			cal.add(Calendar.MINUTE, -1);
			
//			Calendar cal2 =Calendar.getInstance();
//			cal2.setTime(date);
//			
//			cal2.add(Calendar.MINUTE, -1);
			
			while(rs.next()){
				String id = rs.getString("id");
				String recievedate =  rs.getString("recievedate");
				int onoroff = 1;
				int currentonoroff = 0;
				
				Date recieveDate = new Date(new Long(recievedate));
				
				int i = recieveDate.compareTo(cal.getTime());
				
				if(i != 1){
					onoroff = 0;
					currentonoroff = 1;
					
//					updatesetpstmt = con.prepareStatement(updatesetsql);
//					updatesetpstmt.setString(1, id);
//					updatesetpstmt.executeUpdate();
//					updatesetpstmt.close();
					
				}else{
					onoroff = 1;
					currentonoroff = 0;
				}
				updatepstmt.setInt(1, onoroff);
				updatepstmt.setString(2, id);
				updatepstmt.setInt(3, currentonoroff);
				updatepstmt.addBatch();
			}
			
			updatepstmt.executeBatch();
			con.commit();
			
			pstmt.close();
			updatepstmt.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JDBCUtilSingle.getInitJDBCUtil().closeConnection(rs, pstmt, con);
			JDBCUtilSingle.getInitJDBCUtil().closeConnection(rs, updatepstmt, con);
		}
		
	}

}
